package cn.hello2018.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author jeymingwu
 * @date 2019/3/11 16:33
 */
public class SmartDownloadAllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/x-msdownload");
        resp.setHeader("Content-Disposition", "attachment;filename=download.zip");

        String path = getServletContext().getRealPath("/") + "file/";
        String[] filenames = req.getParameterValues("filename");
        String str = "";
        String rt = "\r\n";
        ZipOutputStream zipOutputStream = new ZipOutputStream(resp.getOutputStream());

        for (String filename : filenames) {
            str += filename + rt;
            File file = new File(path + filename);
            zipOutputStream.putNextEntry(new ZipEntry(filename));
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] b = new byte[1024];
            int n = 0;
            while ((n = fileInputStream.read(b)) != -1) {
                zipOutputStream.write(b, 0, n);
            }
            zipOutputStream.flush();
            fileInputStream.close();
        }

        zipOutputStream.setComment("file list:" + rt + str);
        zipOutputStream.flush();
        zipOutputStream.close();
    }
}
